class PromiseOnly {
    static target = null;
    constructor(maxNum) {
        this.max = maxNum;
        this._taskQueue = [];
        this.count = 0;
    }
    static getPromiseOnly(num) {
        if (!PromiseOnly.target) {
            PromiseOnly.target = new PromiseOnly(num);
        }
        return PromiseOnly.target;
    }
    add(promise) {
        return new Promise(async (resolve, reject) => {
            if (this.count >= this.max) {
                await new Promise(complate => this._taskQueue.push(complate))
            }
            this.count++;
            promise().then(resolve, reject).finally(() => {
                this.count--;
                if (this._taskQueue.length) {
                    this._taskQueue.shift()();
                }
            });
        })
    }
}

module.exports = PromiseOnly;